<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" style="margin-bottom: 10px">
      <el-row>
        <el-form-item label="客户名称" prop="khname">
          <el-input
            v-model="queryParams.khname"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="总部编号" prop="zbbh">
          <el-input
            v-model="queryParams.zbbh"
            placeholder="请输入总部编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="开票时间">
          <el-date-picker
            v-model="querySj"
            @change="selectTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完工时间">
          <el-date-picker
            v-model="queryWgSj"
            @change="selectWgTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="完工编号" prop="wgbh">
          <el-input
            v-model="queryParams.wgbh"
            placeholder="请输入完工编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否回款">
          <el-checkbox-group v-model="sfhk" size="mini" @change="selectSfhk">
            <el-checkbox border v-for="item in hkList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="开票状态">
          <el-checkbox-group v-model="kphk" size="mini" @change="selectKphk">
            <el-checkbox border v-for="item in sfList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="完工单">
          <el-checkbox-group v-model="wgd" size="mini" @change="selectWszt">
            <el-checkbox border label="ws">完善</el-checkbox>
            <el-checkbox border label="dws">待完善</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" style="margin-right: 10px">重置</el-button>
        <el-form-item label="日期">
          <el-checkbox-group v-model="rq" size="mini" @change="selectRq">
            <el-checkbox label="zt" border>昨天</el-checkbox>
            <el-checkbox label="jt" border>今天</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:wgd:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdateData"
          v-hasPermi="['gd:wgd:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleAllDelete"
          v-hasPermi="['gd:wgd:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:wgd:export']"
        >全部导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleSelectExport"
          v-hasPermi="['gd:ywd:export']"
        >导出选择数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          :disabled="multiple"
          @click="downExcelData"
        >下载完工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleYhyqr"
          v-hasPermi="['gd:ywd:export']"
        >用户已确认</el-button>
      </el-col>
      <el-col :span="1.5" v-if="this.$store.getters.name === 'admin'">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="multiple"
          @click="authData"
          v-hasPermi="['gd:ywd:export']"
        >授权选择数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wgdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed label="总部编号" width="120" align="left" prop="zbbh">
        <template slot-scope="scope">
          <div style="color: #00afff;cursor: pointer;">
            <span @click="showInfo(scope.row)"> {{scope.row.zbbh}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.zbbh)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed label="完工编号" width="120" align="center" prop="wgbh">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.wgbh}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.wgbh)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed label="客户名称" align="left" prop="khname" />
      <el-table-column label="完工日期" align="center" prop="wgrq" width="100" />
      <el-table-column label="是否已开发票" width="100" align="center" prop="sfykfp">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sfykfp === 'Y'" type="success">是</el-tag>
          <el-tag v-else type="warning">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开票日期" align="center" prop="kprq" width="100" />
      <el-table-column label="是否回款" align="center" prop="sfhk" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sfhk === '1'" type="success">是</el-tag>
          <el-tag v-else-if="scope.row.sfhk === '3'" type="warning">否</el-tag>
          <el-tag v-else-if="scope.row.sfhk === '2'">部分回款</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="完工单" align="center" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.fj !== '' && scope.row.fj !== null && scope.row.fj !== undefined" type="success">完善</el-tag>
          <el-tag v-else type="warning">待完善</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="bz" show-overflow-tooltip />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.sfykfp==='Y'"
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="invoice(scope.row, 2)"
          >未开发票</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="invoice(scope.row, 1)"
          >开发票</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-finance"
            @click="returnMoney(scope.row)"
          >回款</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="returnMoneyLog(scope.row)"
          >回款记录</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="scBjd(scope.row)"
          >生成报价单</el-button>
          <el-button
            v-if="updateDelAuth(scope.row.status)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gd:wgd:edit']"
          >修改</el-button>
          <el-button
            v-if="updateDelAuth(scope.row.status)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:wgd:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改完工单对话框 -->
    <form-info v-if="open" :showForm="open" :title="title" :formInfo="form" :ShowBtn="ShowBtn" @close="cancel"></form-info>

    <!-- 回款 -->
    <hk-form v-if="showHk" :show-hk="showHk" :formInfo="form" @close="closeHk"></hk-form>

    <!-- 开发票 -->
    <kfpForm v-if="showKfp" :showKfp="showKfp" :formInfo="form" @close="closeKfp"></kfpForm>

    <!-- 回款日志 -->
    <HkLogList v-if="showLog" :showXcLog="showLog" :logData="logData" @closeHkLog="closeHkLog"></HkLogList>

    <el-dialog title="生成报价单" :visible.sync="showGenBjd" @close="cancelBjd" width="70%" append-to-body>
      <el-form ref="bjdForm" :model="bjdForm" :rules="rulesBjd" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="报价日期" prop="bjrq">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="bjdForm.bjrq"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择报价日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="330px" label="生成的报价单编号是出厂编号 还是 管理编号数据"></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="编号" prop="bjbh">
              <el-radio v-model="bjdForm.bjbh" label="ccbh" border size="medium">出厂编号</el-radio>
              <el-radio v-model="bjdForm.bjbh" label="glbh" border size="medium">管理编号</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="shengChengBjd">确 定</el-button>
        <el-button type="primary" @click="queryLsBjd">查看历史报价单</el-button>
        <el-button @click="cancelBjd">取 消</el-button>
      </div>

      <el-dialog title="生成历史报价单" :visible.sync="showLsBjd" @close="cancelLsbjd" width="60%" append-to-body>
        <el-table
          border
          :data="lsFjList">
          <el-table-column
            prop="fjname"
            header-align="center"
            label="报价单名称">
          </el-table-column>
          <el-table-column
            width="110"
            prop="createTime"
            header-align="center"
            label="生成日期">
          </el-table-column>
          <el-table-column
            width="280"
            header-align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button
                @click="downFile(scope.row)"
                type="primary"
                icon="el-icon-download"
                size="mini"
              >下载</el-button>
              <el-button
                @click="scBjdData(scope.row)"
                type="info"
                icon="el-icon-download"
                size="mini"
              >提取报价单数据</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

    </el-dialog>

  </div>
</template>

<script>
import kfpForm from '@/views/gd/wgd/kfpForm.vue'
import HkForm from '@/views/gd/wgd/HkForm.vue'
import formInfo from './formInfo.vue'
import HkLogList from './hkLogList.vue'
import { listWgd, getWgd, delWgd, updateYhyqrZt, updateWgd, authDatas, genBjd, genBjdData, downExcel } from "@/api/gd/wgd";
import { allListFj, delFj, getFj, getFjById } from '@/api/gd/fj'
import { parseTime } from '@/utils/ruoyi'
import { downLoadZip } from '@/api/zipdownload'
export default {
  name: "Wgd",
  components: { HkLogList, formInfo, HkForm, kfpForm },
  data() {
    return {
      rq: [],
      lsFjList: [],
      showLsBjd: false,
      showGenBjd: false,
      buttonLoading:false,
      // 是否回款
      showHk: false,
      // 开发票
      showKfp: false,
      userName: this.$store.getters.name,
      ShowBtn: true,
      fjId: "",
      fjTitle: "",
      showYwd: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 完工单表格数据
      wgdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zbbh: undefined,
        fj: undefined,
        fjpdf: undefined,
        sfykfp: undefined,
        wgbh: undefined,
        sfhk: undefined,
        yhyqr: undefined,
        params: {
          startTime: '',
          endTime: '',
          startWgTime: '',
          endWgTime: '',
          wszt: '',
          startCreateTime: '',
          endCreateTime: ''
        }
      },
      // 表单参数
      form: {},
      sfList: [],
      hkList: [],
      sfhk: [],
      kphk: [],
      wgd: [],
      querySj: [],
      queryWgSj: [],
      logData: {},
      showLog: false,
      bjdForm: {},
      // 报价单表单校验
      rulesBjd: {
        bjrq: [
          { required: true, message: "请选择报价日期", trigger: "blur" }
        ],
        bjbh: [
          { required: true, message: "请选择编号", trigger: "blur" }
        ]

      },
      sy: false,
    };
  },
  created() {
    if (!this.sy) {
      this.getList();
    }
    this.getDict()
  },
  watch: {
    '$route': {
      immediate: true,
      async handler(route) {
        if (route.query.sy === "true") {
          await this.resetData()
          switch (route.query.type) {
            case "dlwgdjt":  // 用户已确认完工单
              this.queryParams.yhyqr = "1"
              break
            case "wkfp":  // 未开发票
              this.queryParams.sfykfp = "N"
              break
            case "whk":  // 是否回款
              this.queryParams.sfhk = "3"
              break
          }
          this.sy = true
          this.getList()
        }
      },
      deep: true
    },
  },
  methods: {
    selectRq(item) {
      if (item.length > 0) {
        let hasZt = item.some(item => item === 'zt');
        let hasJt = item.some(item => item === 'jt');
        // ===== 获取昨天日期
        let date = new Date()
        const yesterday = new Date(date);
        yesterday.setDate(yesterday.getDate() - 1); // 减去一天得到昨天的日期
        let zt = this.formatDate(yesterday);
        // ==== 获取今天日期
        let jt = this.formatDate(date);
        // 判断昨天和今天是否已经勾选
        if (hasZt && hasJt) {
          this.queryParams.params.startCreateTime = zt + " 00:00:00"
          this.queryParams.params.endCreateTime = jt + " 23:59:59"
        }else if (hasZt) {
          // 如果只有昨天
          this.queryParams.params.startCreateTime = zt + " 00:00:00"
          this.queryParams.params.endCreateTime = zt + " 23:59:59"
        }else if (hasJt) {
          this.queryParams.params.startCreateTime = jt + " 00:00:00"
          this.queryParams.params.endCreateTime = jt + " 23:59:59"
        }
      }else {
        this.queryParams.params.startCreateTime = ""
        this.queryParams.params.endCreateTime = ""
      }
      this.getList()
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    selectWszt(val) {
      this.queryParams.params.wszt = val.toString()
      this.getList()
    },
    scBjdData(row) {
      delete row.createTime
      genBjdData(row, 'blob').then(res => {
        if (res !== null) {
          const binaryData = [];
          binaryData.push(res);
          let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
          const link = document.createElement('a');
          link.href = url
          link.download = "报价单" + this.getTodayDate() + ".xlsx";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      })
    },
    selectSfhk(val) {
      this.queryParams.sfhk = val.toString()
      this.getList()
    },
    selectKphk(val) {
      this.queryParams.sfykfp = val.toString()
      this.getList()
    },
    // 查看历史报价单
    queryLsBjd() {
      if (this.bjdForm.lsbjdid !== '' && this.bjdForm.lsbjdid !== null && this.bjdForm.lsbjdid !== undefined) {
        // 查询附件列表
        allListFj(this.bjdForm.lsbjdid).then(res => {
          this.lsFjList = res
          this.showLsBjd = true
        })
      }else {
        this.$message.error("当前未生成报价单，请先生成报价单")
      }
    },
    cancelLsbjd() {
      this.lsFjList = []
      this.showLsBjd = false
    },
    downFile(file) {
      // 调用删除附件功能，将附件进行删除
      getFjById(file.fjid, 'blob').then(response => {
        const binaryData = [];
        binaryData.push(response);
        let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
        const link = document.createElement('a');
        link.href = url
        link.download = file.fjname;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },
    shengChengBjd() {
      // this.buttonLoading = true
      this.$refs['bjdForm'].validate((valid) => {
        if (valid) {
          genBjd(this.bjdForm).then(res => {
            this.cancelBjd()
            if (res.data !== null && res.data !== undefined && res.data !== "") {
              let obj = res.data
              getFjById(obj.fjid, 'blob').then(response => {
                const binaryData = [];
                binaryData.push(response);
                let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
                const link = document.createElement('a');
                link.href = url
                link.download = obj.fjname;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
              })
            }
          })
        }
      });
    },
    scBjd(row) {
      if (row.fj !== '' && row.fj !== undefined && row.fj !== null) {
        this.$set(this, 'bjdForm', row)
        this.$set(this.bjdForm, 'bjrq', new Date())
        // this.bjdForm = row
        this.showGenBjd = true
      }else {
        this.$message.error("请先上传完工单附件！")
      }
    },
    cancelBjd() {
      this.$refs['bjdForm'].resetFields();
      this.showGenBjd = false
      this.getList()
    },
    getDict() {
      this.getDicts("sys_yes_no").then(res => {
        this.sfList = res.data
      })
      // 是否回款
      this.getDicts("gd_sfhk").then(res => {
        this.hkList = res.data
      })
    },
    selectTime(time) {
      this.queryParams.params.startTime = time[0]
      this.queryParams.params.endTime = time[1]
    },
    selectWgTime(time) {
      this.queryParams.params.startWgTime = time[0]
      this.queryParams.params.endWgTime = time[1]
    },
    // 回款日志
    returnMoneyLog(row) {
      this.logData = row
      this.showLog = true
    },
    closeHkLog() {
      this.logData = {}
      this.showLog = false
    },
    // 回款
    returnMoney(row) {
      this.form = row
      this.form.sfhk = "1"
      this.form.hkje = ""
      this.form.hksj = ""
      this.showHk = true
    },
    cancelHk() {
      this.showHk = false
      this.reset()
    },
    updateDelAuth(status) {
      return this.userName === 'admin' || status === '1'
    },
    invoice(row, item) {
      getWgd(row.id).then(res => {
        this.form = res.data
        // 未开发票按钮
        if (item === 1) {
          this.showKfp = true
          this.form.kprq = new Date()
        }else {
          // 如果当前状态是已经开发票状态
          this.$modal.confirm("请确认是否要更改为：未开发票 状态").then(() => {
            this.loading = true;
            this.$set(this.form, 'sfykfp', 'N')
            this.$set(this.form, 'fpph', '')
            updateWgd(this.form).then(response => {
              this.$modal.msgSuccess("已设置为：未开票状态！");
              this.loading = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          })
        }
      })

    },
    // ======  上传开始  ======
    handleSuccess(response, file) {
      if(this.ShowBtn) {
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.fj = response.fj
        this.form.fjpdf = response.fjpdf
        if (this.form.id !== undefined) {
          updateWgd(this.form).then(objs => {
            getWgd(this.form.id).then(async response => {
              this.fjList = []
              let obj = response.data
              if (obj.fjpdf !== "" && obj.fjpdf !== null && obj.fjpdf !== undefined) {
                await getFj(obj.fjpdf).then(res => {
                  if (res.data !== null) {
                    const data = {
                      fjid: res.data.fjid,
                      name: res.data.fjname,
                      path: res.data.fjpath
                    }
                    this.fjList.push(data)
                  }
                })
              }
              if (obj.fj !== "" && obj.fj !== null && obj.fj !== undefined) {
                await getFj(obj.fj).then(res => {
                  if (res.data !== null) {
                    const data = {
                      fjid: res.data.fjid,
                      name: res.data.fjname,
                      path: res.data.fjpath
                    }
                    this.fjList.push(data)
                  }
                })
              }
            })
          })
        }
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      if (this.ShowBtn) {
        let fjId = []
        fjId.push(file.fjid)
        let ids = fileList.filter(item => item.id !== file.id).map(item => item.id).toString()
        delFj(fjId).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功！")
            // 删除后更新数据
            if (ids !== '' && ids !== null) {
              this.form.fj = ids
              updateWgd(this.form).then(objs => {
                getWgd(this.form.id).then(async response => {
                  // this.fjList = []
                  fileList = []
                  let obj = response.data
                  if (obj.fjpdf !== "" && obj.fjpdf !== null && obj.fjpdf !== undefined) {
                    await getFj(obj.fjpdf).then(res => {
                      if (res.data !== null) {
                        const data = {
                          fjid: res.data.fjid,
                          name: res.data.fjname,
                          path: res.data.fjpath
                        }
                        // this.fjList.push(data)
                        fileList.push(data)
                      }
                    })
                  }
                  if (obj.fj !== "" && obj.fj !== null && obj.fj !== undefined) {
                    await getFj(obj.fj).then(res => {
                      if (res.data !== null) {
                        const data = {
                          fjid: res.data.fjid,
                          name: res.data.fjname,
                          path: res.data.fjpath
                        }
                        // this.fjList.push(data)
                        fileList.push(data)
                      }
                    })
                  }
                })
              })
            }
          }
        })
      }else {
        this.fjList = fileList
        this.$message.error("当前是预览状态，禁止删除")
      }

    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`);
    },
    // 文件点击回调
    handlePreview(file) {
      let suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (suffix === 'pdf') {
        this.showPdf = true
        this.fjId = file.fjid
        this.fjTitle = "PDF预览"
      }else if (suffix === 'xlsx' || suffix === 'xls') {
        getFjById(file.fjid, 'blob').then(response => {
          const binaryData = [];
          binaryData.push(response);
          let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
          const link = document.createElement('a');
          link.href = url
          link.download = file.name;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
      }

    },
    cancelPdf() {
      this.showPdf = false
    },
    // ======  上传结束  ====
    copyText(data) {
      // const clipboardObj = navigator.clipboard;
      // clipboardObj.writeText(data)
      const textarea = document.createElement('textarea');
      textarea.value = data;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        // 尝试执行复制操作
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("已复制！")
        } else {
          this.$message.error("复制失败！")
        }
      } catch (error) {
        this.$message.error("复制失败！")
      }
      document.body.removeChild(textarea);
    },
    showInfo(row) {
      getWgd(row.id).then(response => {
        this.form = response.data
        this.open = true
        this.ShowBtn = false
        this.title = "业务单信息";
      })
    },
    closeDialog() {
      this.showYwd = false
    },
    /** 查询完工单列表 */
    getList() {
      this.loading = true;
      listWgd(this.queryParams).then(response => {
        this.wgdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.fjList = []
      this.ShowBtn = true
      this.open = false;
      this.reset();
      this.getList()
    },
    closeHk() {
      this.showHk = false
      this.form = {}
      this.getList()
    },
    closeKfp() {
      this.showKfp = false
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        zbbh: undefined,
        fj: undefined,
        fjpdf: undefined,
        sfykfp: 'N',
        createBy: this.$store.getters.nickName,
        createTime: parseTime(new Date()),
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetData() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        zbbh: undefined,
        fj: undefined,
        fjpdf: undefined,
        sfykfp: undefined,
        wgbh: undefined,
        params: {
          startTime: '',
          endTime: '',
          startWgTime: '',
          endWgTime: '',
          wszt: '',
          startCreateTime: '',
          endCreateTime: ''
        }
      }
      this.querySj = []
      this.rq = []
      this.resetForm("queryForm");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          zbbh: undefined,
          fj: undefined,
          fjpdf: undefined,
          sfykfp: undefined,
          wgbh: undefined,
          params: {
            startTime: '',
            endTime: '',
            startWgTime: '',
            endWgTime: '',
            wszt: '',
            startCreateTime: '',
            endCreateTime: ''
          }
      }
      this.querySj = []
      this.rq = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加完工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getWgd(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改完工单";
      });
    },
    handleUpdateData() {
      this.loading = true;
      this.reset();
      const ids = this.ids
      // const obj = this.wgdList.filter(item => ids.some(id => id === item.id))
      // if (obj.length > 0 && obj[0].status === '0' && this.userName !== 'admin') {
      //   this.$message.error("您无权限修改 编号为："  + obj[0].zbbh + " 客户为： " + obj[0].khname + " 业务数据")
      //   this.loading = false;
      // }else {
      //   getWgd(ids).then(response => {
      //     if (response.data.fj !== "" && response.data.fj !== null && response.data.fj !== undefined) {
      //       getFj(response.data.fj).then(res => {
      //         if (res.data !== null) {
      //           const obj = {
      //             fjid: res.data.fjid,
      //             name: res.data.fjname,
      //             path: res.data.fjpath
      //           }
      //           this.fjList.push(obj)
      //         }
      //       })
      //     }
      //     if (response.data.fjpdf !== "" && response.data.fjpdf !== null && response.data.fjpdf !== undefined) {
      //       getFj(response.data.fjpdf).then(res => {
      //         if (res.data !== null) {
      //           const obj = {
      //             fjid: res.data.fjid,
      //             name: res.data.fjname,
      //             path: res.data.fjpath
      //           }
      //           this.fjList.push(obj)
      //         }
      //       })
      //     }
      //     this.loading = false;
      //     this.form = response.data;
      //     this.open = true;
      //     this.title = "修改完工单";
      //   });
      // }

      getWgd(ids).then(response => {
        if (response.data.fj !== "" && response.data.fj !== null && response.data.fj !== undefined) {
          getFj(response.data.fj).then(res => {
            if (res.data !== null) {
              const obj = {
                fjid: res.data.fjid,
                name: res.data.fjname,
                path: res.data.fjpath
              }
              this.fjList.push(obj)
            }
          })
        }
        if (response.data.fjpdf !== "" && response.data.fjpdf !== null && response.data.fjpdf !== undefined) {
          getFj(response.data.fjpdf).then(res => {
            if (res.data !== null) {
              const obj = {
                fjid: res.data.fjid,
                name: res.data.fjname,
                path: res.data.fjpath
              }
              this.fjList.push(obj)
            }
          })
        }
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改完工单";
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('请确认是否删除编号为： ' + row.zbbh + ' 客户为： ' + row.khname + ' 的数据?').then(() => {
        this.loading = true;
        return delWgd(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleYhyqr() {
      const ids = this.ids;
      const data = this.wgdList.filter(item => ids.some(id => id === item.id))
      let obj = ""
      data.forEach((item, index) => {
        if (index === data.length-1) {
          obj += "编号为：" +item.zbbh + " 客户为： " + item.khname
        }else {
          obj += "编号为：" +item.zbbh + " 客户为： " + item.khname + ", "
        }
      })
      this.$modal.confirm('请确认 ' + obj + ' 用户是否确认?').then(() => {
        this.loading = true;
        return updateYhyqrZt(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 批量删除按钮操作 */
    handleAllDelete() {
      const ids = this.ids;
      const data = this.wgdList.filter(item => ids.some(id => id === item.id))
      // 查询当前不可以删除的数据
      let obj = ""
      data.forEach((item, index) => {
        if (index === data.length-1) {
          obj += "编号为：" +item.zbbh + " 客户为： " + item.khname
        }else {
          obj += "编号为：" +item.zbbh + " 客户为： " + item.khname + ", "
        }
      })
      this.$modal.confirm('请确认是否删除 ' + obj + ' 的数据?').then(() => {
        this.loading = true;
        return delWgd(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });

    },
    // 下载Excel
    downExcelData() {
      const ids = this.ids;
      const data = this.wgdList.filter(item => ids.some(id => id === item.id))
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (obj.length > 200) {
          obj += "..."
          break
        }else {
          if (i === data.length-1) {
            obj += "编号为：" +item.zbbh + " 客户为： " + item.khname
          }else {
            obj += "编号为：" +item.zbbh + " 客户为： " + item.khname + ", "
          }
        }
      }

      this.$modal.confirm('请确认是否要下载 ' + obj+' 业务单的Excel').then(() => {
        this.loading = true;
        // downExcel(ids.toString()).then(res => {
        //   let fileName = this.getFileDownName()
        //   const url = window.URL.createObjectURL(new Blob([res]));
        //   const link = document.createElement('a');
        //   link.href = url;
        //   link.setAttribute('download', '完工单'+fileName+'.zip');
        //   document.body.appendChild(link);
        //   link.click();
        // }).catch(err => { console.log("err", err); this.$message.error(err.message)})
        downLoadZip('/gd/wgd/downExcel', "完工单_"+this.getFileDownName() , ids.toString())
      }).finally(() => {
        this.loading = false;
        this.getList();
      });
    },
    getFileDownName() {
      let date = new Date()
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      return `${year}${month}${day}${hours}${minutes}${seconds}`;
    },
    /** 导出按钮操作 */
    handleExport() {
      let name = this.getTodayDate()
      this.download('gd/wgd/export', {
        ...this.queryParams
      }, `${name} 完工单_${new Date().getTime()}.xlsx`)
    },
    handleSelectExport() {
      const ids = this.ids;
      let name = this.getTodayDate()
      this.download('gd/wgd/exportSelectDat/' + ids, {
        ...this.queryParams
      }, `${name} 完工单_${new Date().getTime()}.xlsx`)
    },
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}${month}${day}`;
    },
    authData() {
      const ids = this.ids;
      const data = this.wgdList.filter(item => ids.some(id => id === item.id))
      let obj = ""
      data.forEach((item, index) => {
        if (index === data.length-1) {
          obj += "编号为：" +item.zbbh + " 客户为： " + item.khname
        }else {
          obj += "编号为：" +item.zbbh + " 客户为： " + item.khname + ", "
        }
      })
      this.$modal.confirm('请确认是否要给 ' + obj+' 客户授权').then(() => {
        this.loading = true;
        return authDatas(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("授权成功！");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>
